import Taro from "@tarojs/taro";
import { View, ViewProps } from "@tarojs/components";
import "./index.less";
import { EmptyIcon } from "../Icons";
import { uploadImage } from "@/request";
import { DeleteIcon } from "@/components/Icons";
import ImagePreview from "../ImagePreview";
type Props = {
  url?: string;
  onChange?: (path: string) => void;
} & ViewProps;

const ImageUpload = ({ url, onChange, className, ...others }: Props) => {
  const handleChooseImage = () => {
    Taro.chooseImage({
      count: 1,
      sizeType: ["compressed"],
      sourceType: ["album", "camera"],
      success: async (res) => {
        const file = res.tempFiles[0];
        if (file.size > 500 * 1024) {
          Taro.showToast({
            title: "图片大小不能超过500k",
            icon: "none",
          });
          return;
        }

        const image = await uploadImage(file.path);
        onChange?.(image?.data?.url);
      },
    });
  };

  const handleDelImage = () => {
    onChange?.("");
  };

  return (
    <View className={`image-upload ${className}`} {...others}>
      <View className="image-placeholder">
        {url ? (
          <>
            <ImagePreview src={url} />
            <DeleteIcon
              type="danger"
              style={{ position: "absolute", right: "0", top: "0" }}
              onClick={handleDelImage}
            />
          </>
        ) : (
          <View
            style={{
              width: "100%",
              height: "100%",
              display: "flex",
              justifyContent: "center",
              alignItems: "center",
            }}
            onClick={handleChooseImage}
          >
            <EmptyIcon type="default" size={2} />
          </View>
        )}
      </View>
    </View>
  );
};
export default ImageUpload;
